<template>
  <div class="container">
    <Breadcrumb :items="['检测管理', '地址管理']" />
    <a-card class="general-card" title="地址管理">
      <a-row>
        <a-col :flex="1">
          <a-form :model="formModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left">
            <!-- URL -->
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="检测的URL">
                  <a-input v-model="formModel.url" placeholder="请输入页面关键字" />
                </a-form-item>
              </a-col>
              <!-- 邮箱 -->
              <a-col :span="8">
                <a-form-item label="负责人邮箱">
                  <a-input v-model="formModel.manager" placeholder="请输入负责人邮箱地址" />
                </a-form-item>
              </a-col>
              <!-- 检测结果 -->
              <a-col :span="8">
                <a-form-item field="contentType" label="检测结果">
                  <a-select v-model="formModel.pass" :options="resultTypeOptions" />
                </a-form-item>
              </a-col>
              <!-- 数据筛选 -->
              <a-col :span="8">
                <a-form-item field="contentType" label="数据筛选">
                  <a-select v-model="formModel.filterType" :options="filterTypeOptions" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="ishowDialog = !ishowDialog">
              <template #icon>
                <icon-plus />
              </template>
              添加URL
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="12" style="display: flex; align-items: center; justify-content: end">
          <a-tooltip :content="$t('searchTable.actions.refresh')">
            <div class="action-icon" @click="search"><icon-refresh size="18" /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('searchTable.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption v-for="item in densityList" :key="item.value" :value="item.value" :class="{ active: item.value === size }">
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('searchTable.actions.columnSetting')">
            <a-popover trigger="click" position="bl" @popup-visible-change="popupVisibleChange">
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div v-for="(item, index) in showColumns" :key="item.dataIndex" class="setting">
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox v-model="item.checked" @change="handleChange($event, item as TableColumnData, index)"> </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="false"
        :size="size"
        @page-change="onPageChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <template #operations="{ record }">
          <a-button type="text" size="small"> 检测结果 </a-button>
          <a-button type="text" size="small"> 重新检测 </a-button>
          <a-button type="text" size="small" @click="showDeleteDialog(record)"> 删除 </a-button>
        </template>
      </a-table>
      <a-pagination :total="200" show-page-size />
    </a-card>
    <a-modal v-model:visible="ishowDialog" :on-before-ok="addURL" @cancel="handleCancel" unmountOnClose>
      <template #title> 添加URL </template>
      <div>
        <a-form :model="addURLFormData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left">
          <!-- URL -->
          <a-row>
            <a-form-item label="检测的URL">
              <a-input v-model="addURLFormData.url" placeholder="请输入页面URL" />
            </a-form-item>
          </a-row>
          <a-row>
            <!-- 邮箱 -->
            <a-form-item label="负责人邮箱">
              <a-input v-model="addURLFormData.manager" placeholder="请输入负责人邮箱地址" />
            </a-form-item>
          </a-row>
        </a-form>
      </div>
    </a-modal>
    <a-modal :visible="isshowDeleteDialog" :on-before-ok="deleteRecord" @cancel="closeDeleteDialog" >
      <template #title> 温馨提示 </template>
      <div>是否确认删除选中URL?</div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import { queryScanListData, addSCANURL } from '@/api/scanManage/scanlist';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { queryPolicyList, PolicyRecord, PolicyParams } from '@/api/list';
  import { Pagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const generateFormModel = () => {
    return {
      url: '', //检测地址模糊查询
      manager: '', //邮箱地址
      pass: '', //结果类型
      filterType: 'all',
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<PolicyRecord[]>([]);
  const formModel = ref(generateFormModel());
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);
  const ishowDialog = ref(false); //是否显示弹窗
  const isshowDeleteDialog = ref(false);
  const addURLFormData = ref({}); //添加地址数据源
  const size = ref<SizeProps>('medium');
  let deleteRecordId: string = ''; //删除的记录ID
  const basePagination: Pagination = {
    current: 1,
    pageSize: 20,
  };
  const pagination = reactive({
    ...basePagination,
  });
  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);
  const columns = computed<TableColumnData[]>(() => [
    {
      title: t('searchTable.columns.index'),
      dataIndex: 'index',
      slotName: 'index',
    },
    {
      title: 'url',
      dataIndex: 'url',
    },
    {
      title: '负责人',
      dataIndex: 'manager',
    },
    {
      title: '最近检测时间',
      dataIndex: 'updatetime',
    },
    {
      title: '检测结果',
      dataIndex: 'pass',
    },
    {
      title: '操作',
      dataIndex: 'operations',
      slotName: 'operations',
    },
  ]);
  const contentTypeOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.contentType.img'),
      value: 'img',
    },
    {
      label: t('searchTable.form.contentType.horizontalVideo'),
      value: 'horizontalVideo',
    },
    {
      label: t('searchTable.form.contentType.verticalVideo'),
      value: 'verticalVideo',
    },
  ]);
  const resultTypeOptions = computed<SelectOptionData[]>(() => [
    {
      label: '全部',
      value: '',
    },
    {
      label: '通过',
      value: '通过',
    },
    {
      label: '不通过',
      value: '不通过',
    },
  ]);

  const filterTypeOptions = computed<SelectOptionData[]>(() => [
    {
      label: '所有URL',
      value: 'all',
    },
    {
      label: '自己创建的URL',
      value: 'myself',
    },
  ]);
  const statusOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.status.online'),
      value: 'online',
    },
    {
      label: t('searchTable.form.status.offline'),
      value: 'offline',
    },
  ]);
  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );
  const fetchData = async (params: PolicyParams = { current: 1, pageSize: 20 }) => {
    setLoading(true);
    try {
      //兼容一下京东挫代码逻辑
      console.log(params);
      const res = await queryScanListData(params);
      console.log('res', res);
      const { data } = await queryPolicyList(params);
      renderData.value = res.data;

      // renderData.value = data.list;
      pagination.current = params.current;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown as PolicyParams);
  };
  const onPageChange = (current: number) => {
    fetchData({ ...basePagination, current });
  };

  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
  };

  const handleSelectDensity = (val: string | number | Record<string, any> | undefined, e: Event) => {
    size.value = val as SizeProps;
  };

  const handleChange = (checked: boolean | (string | boolean | number)[], column: Column, index: number) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter((item) => item.dataIndex !== column.dataIndex);
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };

  const exchangeArray = <T extends Array<any>>(array: T, beforeIdx: number, newIdx: number, isDeep = false): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(beforeIdx, 1, newArray.splice(newIdx, 1, newArray[beforeIdx]).pop());
    }
    return newArray;
  };

  const handleCancel = () => {
    ishowDialog.value = false;
    addURLFormData.value = {};
  };
  /**
   * @description: 添加URL
   * @return {*}
   */
  const addURL = async () => {
    console.log(addURLFormData.value, !(addURLFormData.url && addURLFormData.manager));
    if (!(addURLFormData.url && addURLFormData.manager)) {
      try {
        return false;
      } catch (error) {
        console.log(error);
      }
    }
    const data = await addSCANURL(addURLFormData.value);
    if (data.status == 0) {
      window.alert(data.msg);
    }
    console.log(data);

    return false;
  };

  /**
   * @description: 添加URL
   * @return {*}
   */
  const showDeleteDialog = (record: any) => {
    isshowDeleteDialog.value = true;
    deleteRecordId.value = record.id;
  };
  /**
   * @description: 添加URL
   * @return {*}
   */
  const closeDeleteDialog = (record: any) => {
    isshowDeleteDialog.value = false;
    deleteRecordId.value = '';
  };

  /**
   * @description: 删除记录
   * @return {*}
   */
  const deleteRecord = () => {
    console.log('111');
  };
</script>

<script lang="ts">
  export default {
    name: 'SearchTable',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
